#include <54func.h>
//目标：按照ABC的顺序打印A、B、C，
typedef struct shareRes_s{
    int flag;//0 A未完成 1 A完成 2 B完成 3 C完成
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}shareRes_t;
void *threadFunc(void *arg)
{
    shareRes_t * pshareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pshareRes->mutex);
    while(pshareRes->flag != 1)//A还没有做，则B一直陷入死循环，等待直至A完成
    {
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);
    }
    //退出也是带锁的，在这里执行B不是共享资源，因此B就不需要在加锁
    pthread_mutex_unlock(&pshareRes->mutex);
    printf("B\n");
    //接下来要执行C
    pthread_mutex_lock(&pshareRes->mutex);
    pshareRes->flag = 2;
    pthread_cond_signal(&pshareRes->cond);
    pthread_mutex_unlock(&pshareRes->mutex);
    pthread_exit(NULL);
}
int main()
{
    shareRes_t shareRes;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);

    pthread_t tid;
    pthread_create(&tid,NULL,threadFunc,&shareRes);

    printf("A\n");
    pthread_mutex_lock(&shareRes.mutex);
    shareRes.flag = 1;
    pthread_cond_signal(&shareRes.cond);
    pthread_mutex_unlock(&shareRes.mutex);
    pthread_mutex_lock(&shareRes.mutex);
    while(shareRes.flag != 2)//若是B还未完成，则C一直等待在，直至B完成
    {
        pthread_cond_wait(&shareRes.cond,&shareRes.mutex);
    }
    pthread_mutex_unlock(&shareRes.mutex);
    printf("C\n");
    pthread_join(tid,NULL);
    return 0;
}
